#include "hal.h"

/* Transmit setup */
static I2C_M_SETUP_Type i2c_tx;
/* Receive setup */
static I2C_M_SETUP_Type i2c_rx;

/**********************************************************************************
 * Descrição:
 *
 * Paramêtro(s):
 *					-
 * Retorno:
 *					-
 **********************************************************************************/
void hal_sensors_i2c_init (void){
	PINSEL_CFG_Type PinCfg;

	/*configuração da I2C0*/
	PinCfg.OpenDrain = 0;
	PinCfg.Pinmode = 0;
	PinCfg.Funcnum = 1;
	PinCfg.Pinnum = 27;
	PinCfg.Portnum = 0;
	PINSEL_ConfigPin(&PinCfg);
	PinCfg.Pinnum = 28;
	PINSEL_ConfigPin(&PinCfg);

	/*Inicializa o periférico da I2C0*/
	I2C_Init(LPC_I2C0, 200000);

	/* Habilita a operação da I2C0 */
	I2C_Cmd(LPC_I2C0, ENABLE);

}
/**********************************************************************************
 * Descrição:
 *
 * Paramêtro(s):
 *					-
 * Retorno:
 *					-
 **********************************************************************************/

int8_t hal_sensors_i2c_write(uint8_t slave_add, uint8_t *buffer,int16_t size)
{

	i2c_tx.sl_addr7bit = slave_add;
	i2c_tx.tx_data = buffer;
	i2c_tx.tx_length = size;
	i2c_rx.rx_data = NULL;
	i2c_rx.rx_length = 0;
	i2c_rx.retransmissions_max = 3;

	if (I2C_MasterTransferData(LPC_I2C0, &i2c_tx, I2C_TRANSFER_POLLING) == SUCCESS){
		return (0);
	} else {
		return (-1);
	}
}

/**********************************************************************************
 * Descrição:
 *
 * Paramêtro(s):
 *					-
 * Retorno:
 *					-
 **********************************************************************************/
int8_t hal_sensors_i2c_read(uint8_t slave_add, uint8_t *buffer,int16_t size)
{

	i2c_tx.sl_addr7bit = slave_add;
	i2c_tx.tx_data = buffer;		//Substituir pelo comando que deverá ser enviado para obeter a leitura do sensor
	i2c_tx.tx_length = 1;
	i2c_rx.rx_data = buffer;
	i2c_rx.rx_length = size;
	i2c_rx.retransmissions_max = 3;

	if (I2C_MasterTransferData(LPC_I2C0, &i2c_rx, I2C_TRANSFER_POLLING) == SUCCESS){
		return (0);
	} else {
		return (-1);
	}
}

